<extend name="layout/edit" />

<block name="HEADER">

</block>

<block name="CONTENT">
    <control:form id="form" />
</block>

<block name="FOOTER">
   <script type="text/javascript">
    var  page=(function(ns){
    	
		ns.init = function(){
			//显示评论
			if( window.__show_comment == 1){
				$("li[type='grid']").click();
			}
			if( window.__mode != 1){
				form.setReadonly("type",false,false);
			}
			ns.setReadonly();
			ns.setShow();
			form.on("input","give_type",function(e){ ns.setReadonly() });
			form.on("input","type",function(e){ ns.setShow() });
			
			form.$grids['specsGrid'].loadSuccess(function(){
				$("#specsGrid .xw_table_text").eq(0).attr('disabled','disabled');
			});
			form.$grids['specsGrid'].input(function(e,data){
				if(data.field=='stock'){ ns.getTotalStock(); }
			});
			
			if( window.__mode == 3){
				form.setReadonly("give_type",false,false);
				form.setReadonly("freight_id",false,false);
			}
			
			form.on("input","is_gm_upgrade",function(e){  ns.initGmEvent(); });
			ns.initGmEvent();
		}
		
		//初始化是否购买后可升级事件
		ns.initGmEvent = function(){
			if(__mode != 1){
				form.setReadonly('is_gm_upgrade,is_low_level_gm,upgrade_level',false,false);
			}else{
				if( form.getValue('is_gm_upgrade') ==1 ){
					form.setReadonly('is_low_level_gm,upgrade_level',true,true);
				}else{
					form.setReadonly('is_low_level_gm,upgrade_level',false,false);
				}
			}
		}
		
		//设置是否显示
		ns.setShow =function(){
			if( form.getValue('type') == 1){
				$("#setmealGrid").parents('.sections').show();
				form.$grids['setmealGrid'].load();
				$("#specsGrid .layui-btn").hide();
				form.setReadonly("effective_time",false,false);
				form.$el.find("input[name='effective_time']").parents('.table-cell').show();
			}else{
				form.setReadonly("effective_time",false,false);
				form.$el.find("input[name='effective_time']").parents('.table-cell').hide();
				$("#specsGrid .layui-table-tool .layui-btn").show();
				$("#setmealGrid").parents('.sections').hide();
			}
			
			//服务类，只能自提
			if( form.getValue('type') == 1 || form.getValue('type') == 2){
				form.setValue("give_type",0);
				form.setValue("freight_id",'');
				form.setReadonly("give_type",false,false);
				form.setReadonly("freight_id",false,false);
			}else{
				form.setReadonly("give_type",true,true);
			}
		}
		
		//设置是否可以编辑
		ns.setReadonly =function(){
			if( form.getValue('give_type') == 1){
				form.setReadonly("freight_id",true);
			}else{
				form.setReadonly("freight_id",false,false);
				form.setValue("freight_id",'');
			}
		}
		
		//获取总库存
		ns.getTotalStock = function(){
			var totalStock = eval($.map(form.$grids['specsGrid'].getRows(),function(h){
				return h.stock || 0;
			}).join('+'));
			form.setValue('stocks', totalStock.toFixed(0) );
		}
		
		//套餐内商品 - 添加
		ns.addGoods = function(){
	        form.$grids['setmealGrid'].addRow([{
				goods_id:'',
				goods_name:'',
				specs_id:'',
				specs_name:'',
				bar_code:'',
				sale_price:0,
				price:0,
				num:'',
			}]);
		}
		
		//选择商品
		ns.selectGoods = function(){
	        var filter = {
	            url:"modules/common/selectGoods",
	            mode:1,
	            type:2
	        }
	        $.openIframe(filter,"选择商品",['600px', '480px']);
		}
    	ns.selectGoodsCallback = function(ids,data){
    		var selectedRow = form.$grids['setmealGrid'].getSelectedRows()[0];
    		form.$grids['setmealGrid'].update(selectedRow.LAY_TABLE_INDEX,{
    			'goods_name': data[0]['name'],
    			'goods_id': data[0]['id'],
    			'bar_code':data[0]['bar_code'],
    			'specs_name': '',
    			'specs_id': '',
				'sale_price':0,
    		});
    	}
		//套餐内商品 - 删除
		ns.deleteGoods = function(){
			form.$grids['setmealGrid'].deleteRow();    
		}
		
		//商品选择规格
		ns.selectSpecs = function(){
			setTimeout(function(){
				var selectedRow = form.$grids['setmealGrid'].getSelectedRows()[0];
				if(!selectedRow) return $.toast(0,"请先选择商品!");
		        var filter = {
		            url:"modules/common/selectGoodsSpecs",
		            mode:1,
		            goods_id:selectedRow.goods_id
		        }
		        $.openIframe(filter,"选择商品规格",['600px', '480px']);
			},10);
		}
    	ns.selectSpecsCallback = function(ids,data){
    		var selectedRow = form.$grids['setmealGrid'].getSelectedRows()[0];
    		form.$grids['setmealGrid'].update(selectedRow.LAY_TABLE_INDEX,{
    			'specs_name': data[0]['name'],
    			'specs_id': data[0]['id'],
    			'sale_price': data[0]['sale_price'],
    		});
    	}
		
		
		//规格添加行
		ns.addRow = function(){
			form.$grids['specsGrid'].addRow([{
				name:'',
				bar_code:'',
				status:'1',
				stock:'',
				price:'',
				sale_price:'',
				cost_price:'',
				use_integral:'',
				use_price:'',
				is_default:0,
				goods_id:'',
				sort_no:'',
			}]);
			$("#specsGrid .xw_table_text").eq(0).attr('disabled','disabled');
		}
		//规格删除行
		ns.deleteRow = function(){
			form.$grids['specsGrid'].deleteRow();   
			ns.getTotalStock();
		}
		
		//礼包
		ns.giftBag = function(id){
			var specsData = form.$grids['specsGrid'].getSelectedRows();
			window.__gift_bag = specsData[0].gift_bag;
	        var filter = {
	            url: $.getModule('edit_giftbag'),
	            specs_id: id == 'id' ? 0 : id
	        }
	        $.openIframe(filter, "详情",['700px', '450px']);
		}
		//礼包回调
		ns.giftBagCallback = function(data){
			form.$grids['specsGrid'].getSelectedRows()[0].gift_bag = data;
			$.toast(1,'数据已录入，保存后生效！');
		}
		
		
		//抽佣
		ns.draw = function(id){
    		var specsData = form.$grids['specsGrid'].getSelectedRows();
			window.__draws = specsData[0].draws;
	        var filter = {
	            url: $.getModule('edit_draw'),
	            specs_id: id == 'id' ? 0 : id
	        }
	        $.openIframe(filter, "抽佣设置",['700px', '450px']);
		}
		//抽佣回调
		ns.drawCallback = function(data){
			form.$grids['specsGrid'].getSelectedRows()[0].draws = data;
			$.toast(1,'数据已录入，保存后生效！');
		}
        
        //保存
        ns.save=function(){
        	var goodsData = form.$grids['setmealGrid'].getRows();
        	var specsData = form.$grids['specsGrid'].getRows();
        	var param = form.getData();
        	if(!param) return false;
        	if(!param.cate_id){
        		return $.toast(0,'请选择所属分类！');
        	};
        	if(!param.img){
        		return $.toast(0,'请上传商品主图！');
        	};
        	if(!param.banners){
        		return $.toast(0,'请上传商品轮播图！');
        	};
        	if(param.type==1 && !goodsData[0]){
        		return $.toast(0,'套餐内商品列表不能为空！');
        	}
        	form.save(4).then(function(res){
        		$.ajaxs('/admin/v1/goods/addOrUpdateChilds',{
        			goods_id:res.data,
	        		goodsData: JSON.stringify($.map(goodsData,function(h){
	        			if(!h.id) delete h.id;
	        			h.pid = res.data;
	        			return h;	
	        		})),
	        		specsData: JSON.stringify($.map(specsData,function(h){
	        			if(!h.id) delete h.id;
	        			h.goods_id = res.data;
	        			return h;	
	        		})),
	        	}).then(function(){
					form.opener.grid.load();
					form.opener.$.toast(1,"保存成功！");
					if(window.__mode==1){
						$.setRequest({oid:res.data,mode:2});
					}else{
						form.$grids['setmealGrid'].load();
						form.$grids['specsGrid'].load();
					}
	    		});
        	});
        }
        return ns;
    }({}));
    
    $(function(){ page.init(); });
   </script>
</block>



